Practical-06
Mobile Application
Practical List
Create an android program that will display the use of a menu that will change the color of the background screen after selecting a menu option.
Steps
- Create a new Android project in Android Studio.
- Open the
activity_main.xmllayout file. - Add a
TextViewelement to the layout with the following attributes:android:id="@+id/textView"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="Background Color Changer"android:textSize="24sp"
- Open the
MainActivity.javafile. - Inside the
onCreatemethod, add the following code to set the content view to theactivity_main.xmllayout:setContentView(R.layout.activity_main); - Create a new method called
showColorMenuto display the color menu options:private void showColorMenu() {
PopupMenu popupMenu = new PopupMenu(this, findViewById(R.id.textView));
popupMenu.getMenuInflater().inflate(R.menu.color_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int color = 0;
switch (item.getItemId()) {
case R.id.menu_red:
color = Color.RED;
break;
case R.id.menu_green:
color = Color.GREEN;
break;
case R.id.menu_blue:
color = Color.BLUE;
break;
}
findViewById(R.id.textView).setBackgroundColor(color);
return true;
}
});
popupMenu.show();
} - Create a new XML file called
color_menu.xmlin theres/menudirectory. - Open the
color_menu.xmlfile and add the following code to define the color menu options:<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_red"
android:title="Red" />
<item
android:id="@+id/menu_green"
android:title="Green" />
<item
android:id="@+id/menu_blue"
android:title="Blue" />
</menu> - Open the
activity_main.xmllayout file. - Add a button element below the
TextViewwith the following attributes:android:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Change Color"
- Open the
MainActivity.javafile. - Inside the
onCreatemethod, add the following code to set a click listener for the button:Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showColorMenu();
}
}); - Run the application on an Android device or emulator.
- Click the "Change Color" button to display the color menu.
- Select a color option from the menu to change the background color of the text view.
Congratulations! You have successfully created an Android program that displays the use of a menu to change the color of the background screen.